package thread.learn.objectSafe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 面试官：你知道如何发布或共享一个对象吗？
 *
 * 发布对象：使一个对象能够被其他线程、其他作用域的代码所使用。
 *
 *
 */
public class Main {
    //final 加了也没用
    private  String[] strs = {"1", "2", "3"};

    public String[] getStrs() {
        return strs;
    }

    //变量逸出原有作用域
    public static void main(String[] args) {
        Main m1 = new Main();
        System.out.println(Arrays.toString(m1.getStrs()));
        m1.getStrs()[0] = "4";
        System.out.println(Arrays.toString(m1.getStrs()));

        ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
        map.put("1",1);
        map.replace("1",2);
        map.get("1");
        System.out.println(map);

        ListHelper<Integer> lists = new ListHelper<>();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {

                lists.putIfAbsent(finalI);
            }, "thread-name").start();
        }
        System.out.println(lists.size());
        System.out.println(lists.list());
    }
}

class ListHelper<E> {
    public List<E> list =
            Collections.synchronizedList(new ArrayList<E>());
    public synchronized boolean putIfAbsent(E x) {
        boolean absent = !list.contains(x);
        if (absent)
            list.add(x);
        return absent;
    }

    public boolean putIfAbsentSafe(E x) {
        synchronized (list) {
            boolean absent = !list.contains(x);
            if (absent)
                list.add(x);
            return absent;
        }
    }
    public int size(){
        return list.size();
    }
    public List<E> list(){
        return list;
    }
}